<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="css/common.css">
    <link rel="stylesheet" href="css/login.css">
</head>
<body>
    <!-- 导航栏 -->
    <div class="nav">
        <!-- 左边 -->
        <div class="nav-left">
            <img src="img/logo2.jpg" alt="">
            <span>我的博客系统</span>
        </div>
    </div>
    <!-- 登录部分 -->
    <div id="login-container">
        <div id="login-form">
            <h3>登录</h3>
            <div class="login-row">
                <span>用户名</span>
                <input type="text" id="username">
            </div>
            <div class="login-row">
                <span>密码</span>
                <input type="password" id="password">
            </div>
            <!-- 用div占据一行，显示报错信息：设置为红色字体 -->
            <div id="error" style="color: red; height: 1.2em;"></div>
            <div class="login-row">
                <input type="submit" id="submit" value="提交">
            </div>
        </div>
    </div>
</body>
<script src="js/util.js"></script>
<script>
    //登录，是点击登录按钮，开始执行
    var btn = document.querySelector("#submit");
    var username = document.querySelector("#username");
    var password = document.querySelector("#password");
    var error = document.querySelector("#error");
    btn.onclick = function(){
        if(!username.value){
            // alert("账号不能为空")
            error.innerHTML = "账号不能为空";
            return;
        }
        if(!password.value){
            // alert("密码不能为空")
            error.innerHTML = "密码不能为空";
            return;
        }
        error.innerHTML = '';
        //发送ajax请求
        ajax({
            method: "POST",
            url: "login", //注意不要加/，但servlet需要加
            contentType: "application/json",
            body: JSON.stringify({ // body中必须是json字符串：把json对象传入stringify转为json字符串
                username: username.value,// 前边的是json数据/请求数据的键，后边的dom元素用户输入的账号的值
                password: password.value,
            }),
            callback: function(status, responseText){
                var json = handleResponse(status, responseText);
                if(!json) return;
                //解析响应正文json
                //登录成功：跳转到博客列表页面
                if(json.ok){
                    location.href = "blog_list.html";
                }else{
                    //报错：显示报错信息
                    // alert(json.error);//先简单弹出窗验证，然后再改为显示
                    error.innerHTML = json.error;
                }
            }
        })
    }
</script>
</html>